package com.example.exceldemo.service.impl;

import com.example.exceldemo.model.TaskStatus;
import com.example.exceldemo.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 任务服务实现类
 * 使用内存缓存存储任务状态
 */
@Slf4j
@Service
public class TaskServiceImpl implements TaskService {

    /**
     * 任务缓存，使用ConcurrentHashMap保证线程安全
     */
    private final Map<String, TaskStatus> taskCache = new ConcurrentHashMap<>();

    @Override
    public TaskStatus createTask(String taskType, String metadata) {
        String taskId = generateTaskId();
        TaskStatus taskStatus = new TaskStatus(taskId, taskType);
        taskStatus.setMetadata(metadata);
        
        taskCache.put(taskId, taskStatus);
        log.info("创建任务: {}, 类型: {}", taskId, taskType);
        
        return taskStatus;
    }

    @Override
    public TaskStatus getTaskStatus(String taskId) {
        TaskStatus taskStatus = taskCache.get(taskId);
        if (taskStatus == null) {
            log.warn("任务不存在: {}", taskId);
        }
        return taskStatus;
    }

    @Override
    public TaskStatus updateTaskProgress(String taskId, int progress) {
        TaskStatus taskStatus = taskCache.get(taskId);
        if (taskStatus == null) {
            log.warn("尝试更新不存在的任务进度: {}", taskId);
            return null;
        }
        
        taskStatus.updateProcessing(progress);
        log.debug("更新任务进度: {}, 进度: {}%", taskId, progress);
        
        return taskStatus;
    }

    @Override
    public TaskStatus completeTask(String taskId, String resultData) {
        TaskStatus taskStatus = taskCache.get(taskId);
        if (taskStatus == null) {
            log.warn("尝试完成不存在的任务: {}", taskId);
            return null;
        }
        
        taskStatus.updateCompleted(resultData);
        log.info("任务完成: {}", taskId);
        
        return taskStatus;
    }

    @Override
    public TaskStatus failTask(String taskId, String errorMessage) {
        TaskStatus taskStatus = taskCache.get(taskId);
        if (taskStatus == null) {
            log.warn("尝试将不存在的任务标记为失败: {}", taskId);
            return null;
        }
        
        taskStatus.updateFailed(errorMessage);
        log.error("任务失败: {}, 错误: {}", taskId, errorMessage);
        
        return taskStatus;
    }
    
    /**
     * 生成唯一任务ID
     * 
     * @return 任务ID
     */
    private String generateTaskId() {
        return UUID.randomUUID().toString().replace("-", "");
    }
} 